package servlet.control;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.attribute.UserPrincipal;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Util.UserProperties;
import model.VUser;

public class LoginFilter extends HttpServlet implements Filter {

	
	

	@Override
	public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
			FilterChain filterChain) throws IOException, ServletException 
	{
		HttpServletRequest request = (HttpServletRequest) sRequest;
		HttpServletResponse response = (HttpServletResponse) sResponse;
		HttpSession session = request.getSession();
		
		String url = request.getServletPath();
		
		if(url.equals(""))
			url+="/";
			url = url.toLowerCase();
		if(url.indexOf(".css")<=0 && url.indexOf(".jpg")<=0 && url.indexOf(".gif")<=0 && url.indexOf(".png")<=0 &&
				url.indexOf(".bmp")<=0 && url.indexOf(".serv")<=0  && url.indexOf(".js")<=0){
			if(!url.endsWith("blogermain.do") && !url.endsWith("blogermain.jsp") &&
					!url.endsWith("bloger.do") && !url.endsWith("bloger.jsp") &&
					!url.endsWith("blogerartil.do") && !url.endsWith("blogerarticle.jsp") &&
					!url.endsWith("login.do") && !url.endsWith("login.jsp") &&
					!url.endsWith("addnormaluser.do") && !url.endsWith("addnormaluser.jsp") &&
					!url.endsWith("updateblogeruser.do") && !url.endsWith("addblogeruser.jsp") &&
					!url.endsWith("safecode.do") && !url.endsWith("loginout.do") &&!url.endsWith("fileuploadservlet.do"))
					{
						VUser loginUser = (VUser)session.getAttribute("loginuser");
						if(loginUser == null || loginUser.getUsertype() == UserProperties.normalusertype){
							response.sendRedirect("login.jsp");
							return;
							}
					}
		}
		filterChain.doFilter(sRequest, sResponse);		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
